import { Provide } from '@midwayjs/decorator';
import { SysUser } from '../../../entity/admin/sys/user';
import { BaseService } from '../../baseService';
import { InjectEntityModel } from '@midwayjs/orm';
import { In, Repository } from 'typeorm';
import { SysRole } from '../../../entity/admin/sys/role';
import {
  CreateUserDto,
  GetUserInfoDao,
  UpdateUserDto,
} from '../../../dto/admin/sys/user';
import { UpdateUserRoleDto } from '../../../dto/admin/sys/userRole';

@Provide()
export class SysUserService extends BaseService {
  @InjectEntityModel(SysUser)
  sysUser: Repository<SysUser>;

  @InjectEntityModel(SysRole)
  sysRole: Repository<SysRole>;

  async getUserInfo(id: GetUserInfoDao): Promise<SysUser> {
    const user: SysUser = await this.sysUser.findOne(id);
    return user;
  }

  async createUser(user: CreateUserDto) {
    const data = await this.sysUser.save(user);
    return data;
  }

  async getUserList() {
    const list = await this.sysUser.find();
    return list;
  }

  async updateUser(user: UpdateUserDto) {
    const data = await this.sysUser.save(user);
    return data;
  }

  async getUserAndRole(id: number) {
    const list = await this.sysUser.findOne(id, { relations: ['role'] });
    return list;
  }

  async updateUserRole(userRole: UpdateUserRoleDto) {
    const roleIds = userRole.roleIds;
    const rolelist = await this.sysRole.find({ id: In(roleIds) });
    const userR: any = userRole;
    userR.role = rolelist;
    const uer = await this.sysUser.save(userR);
    return uer;
  }
}
